package exp;

import utils.BasicJPanel;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;

public class GrayJPanel extends BasicJPanel
{
    private final JLabel imageJLabel;
    private final JLabel grayJLabel;

    public GrayJPanel()
    {
        super();
        setLayout(new GridLayout(1,2));
                add(imageJLabel=new JLabel());
        add(grayJLabel=new JLabel());
    }

    public static int RGBToGray(int rgb)
    {
        final int r=(rgb>>16)&0XFF;
        final int g=(rgb>>8)&0XFF;
        final int b=(rgb)&0XFF;
        return (r+g+b)/3;
    }

    public static int grayToRGB(int t)
    {
        return (t<<16)|(t<<8)|(t);
    }

    public void update(Path path) throws IOException, BmpStructureErrorException
    {
        final Bmp bmp=new Bmp(path);
        imageJLabel.setIcon(new ImageIcon(bmp.getImage()));
        final BufferedImage src=bmp.getImage();
        final BufferedImage dst=new BufferedImage(src.getWidth(),src.getHeight(),BufferedImage.TYPE_INT_RGB);
        for(int i=0;i<src.getHeight();++i)
            for(int j=0;j<src.getWidth();++j)
                dst.setRGB(j,i,grayToRGB(RGBToGray(src.getRGB(j,i))));
        grayJLabel.setIcon(new ImageIcon(dst));
    }

    public String getButtonName()
    {
        return "必做3：灰度化";
    }

}
